package com.xgs.web.controller.system;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xgs.common.annotation.Log;
import com.xgs.common.core.controller.BaseController;
import com.xgs.common.core.domain.AjaxResult;
import com.xgs.common.core.domain.entity.SysUser;
import com.xgs.common.core.domain.model.LoginUser;
import com.xgs.common.core.page.TableDataInfo;
import com.xgs.common.enums.BusinessType;
import com.xgs.common.utils.DateUtils;
import com.xgs.common.utils.StringUtils;
import com.xgs.common.utils.poi.ExcelUtil;
import com.xgs.common.utils.uuid.IdUtils;
import com.xgs.system.domain.BasicVersion;
import com.xgs.system.domain.Roster;
import com.xgs.system.domain.RosterHistory;
import com.xgs.system.service.BasicVersionService;
import com.xgs.system.service.RosterHistoryService;
import com.xgs.system.service.RosterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @author JerryLu
 * @date 2024/10/23 11:05
 * @description 名单录入数据Controller
 */
@RestController
@RequestMapping("/system/roster")
public class RosterController extends BaseController {

    @Autowired
    private BasicVersionService versionService;

    @Autowired
    private RosterService rosterService;

    @Autowired
    private RosterHistoryService historyService;

    /**
     * 查询名单录入数据列表
     */
    @PreAuthorize("@ss.hasPermi('system:roster:list')")
    @GetMapping("/list")
    public TableDataInfo list(Roster roster) {
        startPage();
        if (!SysUser.isAdmin(getUserId())) {
            roster.setDeptId(getDeptId());
        }
        List<Roster> list = rosterService.queryList(roster);
        return getDataTable(list);
    }

    /**
     * 导出名单录入数据列表
     */
    @PreAuthorize("@ss.hasPermi('system:roster:export')")
    @Log(title = "名单录入数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Roster roster) {
        if (!SysUser.isAdmin(getUserId())) {
            roster.setDeptId(getDeptId());
        }
        List<Roster> list = rosterService.queryList(roster);
        ExcelUtil<Roster> util = new ExcelUtil<Roster>(Roster.class);
        util.exportExcel(response, list, "名单录入数据数据");
    }

    /**
     * 获取名单录入数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:roster:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(rosterService.getById(id));
    }

    /**
     * 新增名单录入数据
     */
    @PreAuthorize("@ss.hasPermi('system:roster:add')")
    @Log(title = "名单录入数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Roster roster) {
        QueryWrapper<RosterHistory> query = Wrappers.query();
        query.eq("vehicle_id", formatVehicleId(roster.getVehicleId()));
        query.eq("type", 0);
        query.eq("del_flag", 0);
        query.eq("dept_id", getDeptId());
        if (roster.getType() == 0 && StringUtils.isNotEmpty(roster.getEndRoadNo())) {
            query.eq("end_road_no", roster.getEndRoadNo());
        }
        query.apply("end_date >= TO_TIMESTAMP({0}, 'YYYY-MM-DD HH24:MI:SS')", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, roster.getEndDate()));
        RosterHistory dor = historyService.getOne(query);
        if (dor != null) {
            JSONObject data = new JSONObject();
            data.put("id", dor.getId());
            data.put("version", dor.getVersion());
            data.put("end_time", dor.getEndDate());
            return AjaxResult.error(-2, roster.getVehicleId().split("_")[0] + "已有同路段的数据，请先修改或删除！", data);
        }

        QueryWrapper<RosterHistory> query1 = Wrappers.query();
        query1.eq("vehicle_id", formatVehicleId(roster.getVehicleId()));
        query1.eq("dept_id", getDeptId());
        query1.eq("del_flag", 0);
        if (roster.getType() == 2) {
            query1.eq("en_station_id", roster.getEnStationId());
            query1.eq("ex_station_id", roster.getExStationId());
        }
        query1.apply("end_date >= TO_TIMESTAMP({0}, 'YYYY-MM-DD HH24:MI:SS')", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, roster.getEndDate()));
        long cou = historyService.count(query1);
        if (cou > 0) {
            List<RosterHistory> his = historyService.list(query1);
            JSONObject data = new JSONObject();
            data.put("id", his.get(0).getId());
            data.put("version", his.get(0).getVersion());
            data.put("end_time", his.get(0).getEndDate());
            return AjaxResult.error(-2, roster.getVehicleId().split("_")[0] + "已有相同类型的数据，请先修改或删除！", data);
        }
//        if (his != null) {
//            JSONObject data = new JSONObject();
//            data.put("id", his.getId());
//            data.put("version", his.getVersion());
//            data.put("end_time", his.getEndDate());
//            return AjaxResult.error(-2, roster.getVehicleId().split("_")[0] + "已有相同类型的数据，请先修改或删除！", data);
//        }

        BasicVersion basic = versionService.getById(roster.getBasicId());
        String day = DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD);
        String beginTime = DateUtils.dateTimeNow(day + " 00:00:00");
        String endTime = DateUtils.dateTimeNow(day + " 23:59:59");
        QueryWrapper<RosterHistory> queryWrapper = Wrappers.query();
//        queryWrapper.le("version", basic.getVersion());
        queryWrapper.eq("dept_id", getDeptId());
        queryWrapper.eq("del_flag", 0);
        queryWrapper.like("vehicle_id", formatVehicleId(roster.getVehicleId()));
        queryWrapper.apply("create_time >= TO_TIMESTAMP({0}, 'YYYY-MM-DD HH24:MI:SS')", beginTime);
        queryWrapper.apply("end_date >= TO_TIMESTAMP({0}, 'YYYY-MM-DD HH24:MI:SS')", beginTime);
        queryWrapper.apply("end_date <= TO_TIMESTAMP({0}, 'YYYY-MM-DD HH24:MI:SS')", endTime);
        long count = historyService.count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error(-1, roster.getVehicleId().split("_")[0] + "今天已录入下发过");
        }
        String[] arr = roster.getExStationId().split(",");
        if (roster.getExStationId().contains(",") && arr.length > 0) {
            for (int i = 0; i < arr.length; i++) {
                List<Roster> li = rosterService.queryList(roster);
                if (!li.isEmpty()) {
                    continue;
                } else {
                    roster.setExStationId(arr[i]);
                    roster.setId(IdUtils.fastSimpleUUID());
                    roster.setCreateTime(DateUtils.getNowDate());
                    roster.setDeptId(getDeptId());
                    roster.setSpare3(0);
                    roster.setVehicleId(formatVehicleId(roster.getVehicleId()));
                    rosterService.save(roster);
                }
            }
            return toAjax(1);
        } else {
            List<Roster> li = rosterService.queryList(roster);
            if (!li.isEmpty()) {
                return AjaxResult.error(-1, roster.getVehicleId().split("_")[0] + "已有相同数据");
            }
            roster.setId(IdUtils.fastSimpleUUID());
            roster.setCreateTime(DateUtils.getNowDate());
            roster.setDeptId(getDeptId());
            roster.setSpare3(0);
            boolean i = rosterService.save(roster);
            if (i) {
                if (roster.getIsDouble() == 1 && roster.getType() == 2) {
                    QueryWrapper<Roster> query3 = Wrappers.query();
                    query3.eq("vehicle_id", formatVehicleId(roster.getVehicleId()));
                    query3.eq("type", 2);
                    query3.eq("ex_station_id", roster.getEnStationId());
                    query3.eq("ex_station_hex", roster.getEnStationHex());
                    query3.eq("en_station_id", roster.getExStationId());
                    query3.eq("en_station_hex", roster.getExStationHex());
                    query3.eq("is_double", 1);
                    long count1 = rosterService.count(query3);
                    if (count1 <= 0) {
                        Roster ros = JSON.parseObject(JSON.toJSONString(roster), Roster.class);
                        ros.setId(IdUtils.fastSimpleUUID());
                        ros.setCreateTime(DateUtils.getNowDate());
                        ros.setDeptId(getDeptId());
                        ros.setSpare3(0);
                        ros.setEnStationId(roster.getExStationId());
                        ros.setEnStationHex(roster.getExStationHex());
                        ros.setExStationId(roster.getEnStationId());
                        ros.setExStationHex(roster.getEnStationHex());
                        ros.setVehicleId(formatVehicleId(roster.getVehicleId()));
                        rosterService.save(ros);
                    }
                }
            }
            return toAjax(1);
        }
    }

    /**
     * 导入名单数据
     */
    @PreAuthorize("@ss.hasPermi('system:roster:import')")
    @Log(title = "名单录入数据", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, String basicId) throws Exception {
        ExcelUtil<Roster> util = new ExcelUtil<Roster>(Roster.class);
        List<Roster> rosterList = util.importExcel(file.getInputStream());
        String deptId = getDeptId();
        LoginUser user = getLoginUser();
        String message = rosterService.importRosters(rosterList, true, deptId, user, basicId);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Roster> util = new ExcelUtil<Roster>(Roster.class);
        util.importTemplateExcel(response, "名单数据");
    }

    /**
     * 修改名单录入数据
     */
    @PreAuthorize("@ss.hasPermi('system:roster:edit')")
    @Log(title = "名单录入数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Roster roster) {
        String[] arr = roster.getExStationId().split(",");
        if (roster.getExStationId().contains(",") && arr.length > 0) {
            for (int i = 0; i < arr.length; i++) {
                QueryWrapper<Roster> query = Wrappers.query();
                query.eq("ex_station_id", arr[i]);
                query.eq("id", roster.getId());
                long count = rosterService.count(query);
                if (count > 0) {
                    roster.setExStationId(arr[i]);
                    rosterService.saveOrUpdate(roster);
                } else {
                    if (roster.getType() == 2) {
                        return AjaxResult.error(-1, "已有同类型的站到站数据，禁止再添加");
                    }
                    roster.setExStationId(arr[i]);
                    roster.setId(IdUtils.fastSimpleUUID());
                    roster.setCreateTime(DateUtils.getNowDate());
                    roster.setDeptId(getDeptId());
                    roster.setSpare3(0);
                    rosterService.save(roster);
                    if (roster.getIsDouble() == 1 && roster.getType() == 2) {
                        Roster ros = JSON.parseObject(JSON.toJSONString(roster), Roster.class);
                        ros.setId(IdUtils.fastSimpleUUID());
                        ros.setCreateTime(DateUtils.getNowDate());
                        ros.setDeptId(getDeptId());
                        ros.setSpare3(0);
                        ros.setEnStationId(roster.getExStationId());
                        ros.setEnStationHex(roster.getExStationHex());
                        ros.setExStationId(roster.getEnStationId());
                        ros.setExStationHex(roster.getEnStationHex());
                        rosterService.save(ros);
                    }
                }
            }
            return toAjax(1);
        } else {
            roster.setUpdateTime(DateUtils.getNowDate());
            rosterService.updateById(roster);
            if (roster.getIsDouble() == 1 && roster.getType() == 2) {
                QueryWrapper<Roster> query = Wrappers.query();
                query.eq("vehicle_id", formatVehicleId(roster.getVehicleId()));
                query.eq("type", 2);
                query.eq("ex_station_id", roster.getEnStationId());
                query.eq("ex_station_hex", roster.getEnStationHex());
                query.eq("en_station_id", roster.getExStationId());
                query.eq("en_station_hex", roster.getExStationHex());
                query.eq("is_double", 1);
                long count = rosterService.count(query);
                if (count <= 0) {
                    Roster ros = JSON.parseObject(JSON.toJSONString(roster), Roster.class);
                    ros.setId(IdUtils.fastSimpleUUID());
                    ros.setCreateTime(DateUtils.getNowDate());
                    ros.setDeptId(getDeptId());
                    ros.setSpare3(0);
                    ros.setEnStationId(roster.getExStationId());
                    ros.setEnStationHex(roster.getExStationHex());
                    ros.setExStationId(roster.getEnStationId());
                    ros.setExStationHex(roster.getEnStationHex());
                    rosterService.save(ros);
                }
            }
            return toAjax(1);
        }
    }

    /**
     * 删除名单录入数据
     */
    @PreAuthorize("@ss.hasPermi('system:roster:remove')")
    @Log(title = "名单录入数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(rosterService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 车牌格式化，转大写，去除车牌中的"."(军车、武警车会有的情况)
     *
     * @param vehicleId
     * @return
     */
    public String formatVehicleId(String vehicleId) {
        return vehicleId.toUpperCase().replace(".", "").trim();
    }
}
